package com.lean.android.adsdk

import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import com.qmuiteam.qmui.kotlin.throttleClick

/**
 * Created by ivan on 08/02/2018.
 */
fun View.gone() {
    visibility = View.GONE
}

fun View.invisible() {
    visibility = View.INVISIBLE
}

fun View.visible() {
    visibility = View.VISIBLE
}

fun View.show(show:Boolean){
    if(show) visible() else gone()
}

fun View.isVisible(): Boolean = visibility == View.VISIBLE
fun View.isGone(): Boolean = visibility == View.GONE


fun View.onThrottleClick(wait: Long = 200, block: ((View) -> Unit)) {
    setOnClickListener(throttleClick(wait, block))
}

fun View.enableDragAndDrop(){
    var dx = 0F
    var dy = 0F
    var lastAction = -1
    var initialRawX = 0F
    var initialRawY = 0F
    val slop = ViewConfiguration.get(context).scaledTouchSlop
    setOnTouchListener { v, event ->
        when(event.actionMasked){
            MotionEvent.ACTION_DOWN -> {
                initialRawX = event.rawX
                initialRawY = event.rawY
                dx = v.x - event.rawX
                dy = v.y - event.rawY
                lastAction = MotionEvent.ACTION_DOWN

            }
            MotionEvent.ACTION_MOVE -> {
                v.x = event.rawX + dx
                v.y = event.rawY + dy
                lastAction = MotionEvent.ACTION_MOVE
            }
            MotionEvent.ACTION_UP -> {
                val xDiff = event.rawX - initialRawX
                val yDiff = event.rawY - initialRawY
                if(xDiff < slop && yDiff < slop){
                    performClick()
                    return@setOnTouchListener false
                }
            }
            else -> {
                return@setOnTouchListener false
            }
        }
        return@setOnTouchListener true
    }
}